package com.lcc.service.impl;

import com.lcc.mapper.DeptMapper;
import com.lcc.mapper.EmpMapper;
import com.lcc.pojo.Dept;
import com.lcc.pojo.DeptLog;
import com.lcc.service.DeptLogService;
import com.lcc.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    //写入deptMapper 进行数据库操作
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogService deptLogService;

    //查询部门所以数据
    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    //@Transactional(rollbackFor = Exception.class) //所以异常都会回滚
    @Transactional
    //根据ID删除数据
    @Override
    public void delete(Integer id) {
        try {
            deptMapper.deleteById(id);//根据ID删除部门数据
            //int i = 1 / 0; //出错点，加上注解后出错Spring不会删除数据库数据
            empMapper.deleteByDeptId(id);//根据部门ID删除该部门下的员工
        } finally { //无论以上代码是否执行成功，记录日志都会执行。
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了解散部门的操作哦，此次解散的是" + id + "号部门");
            deptLogService.insert(deptLog);
        }
    }

    //新增数据
    @Override
    public void add(Dept dept) {
        //补全操作时间
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }

    //根据ID查询指定部门信息
    @Override
    public Dept selectById(Integer id) {
        Dept dept = deptMapper.selectById(id);
        return dept;
    }

    //修改部门名称
    @Override
    public void alter(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.alter(dept);
    }
}
